const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const path = require("path");
const app = express();
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 创建与数据库的连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root', // mysql的用户名
  password: '123456', // mysql的密码
  database: 'register'
});
 
// 连接到数据库
connection.connect((err) => {
  if (err) throw err;
  console.log('连接数据库成功');
});
 
/**
 *  注册页面
 */
app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "views", "register.html")); 
});
app.get("/success", (req, res) => {
  res.sendFile(path.join(__dirname, "views", "success.html")); 
}); 
/**
 *  注册接口
 */
app.post("/register", (req, res) => {  
    // 用户名,密码，性别，年龄，邮箱地址，注册时间
    const username = req.body.username;
    const password = req.body.password;
    const gender = req.body.gender;
    const age = req.body.age;
    const emailaddress = req.body.email;
    const registertime = new Date();
    		// 创建一个新用户
    		const user = {username, password,gender,age,emailaddress,registertime};
    		// 将新用户插入到数据库中
		    connection.query('INSERT INTO users SET ?', user, (err, result) => {
          if(err){
            if(err.code=="ER_DUP_ENTRY")
              res.json({success:false,message:"用户名重复"})
            else
              res.json({success:false,message:"未知错误"})
          }
          else{
            res.json({success:true,message:"注册成功"})
          } 
		    });
});
app.listen(8081, ()=> {
	console.log("http://127.0.0.1:8081");
})